﻿using NHibernate.Criterion;
using Online_Course.Core;
using Online_Course.Domain;
using Online_Course.Service;
using Online_Course.Web.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Online_Course.Web.Controllers
{
    public class TeacherController : Controller
    {
        //
        // GET: /Teacher/
        #region 列表
        public ActionResult Index(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件记录总数
            int count = 0;
            IList<Order> listOrder = new List<Order>() { new Order("ID", true) };
            IList<Teacher> list = Container.Instance.Resolve<ITeacherService>().Query(new List<ICriterion>() { new LikeExpression("Name", "%" + qryUserName + "%") }, listOrder, pageIndex, PagerHelper.PageSize, out count);
            //转换为PageList集合
            PageList<Teacher> pageList = list.ToPageList<Teacher>(
                pageIndex
                , PagerHelper.PageSize
                , count);
            return View(pageList);//用pageList集合填充页面。
        }
        #endregion

        #region 新增
        public ActionResult Create()
        {
            Teacher teacher = new Teacher();
            //获取所有教师
            IList<Teacher> lst = Container.Instance.Resolve<ITeacherService>().GetAll();
            IList<SelectListItem> lstteacher = new List<SelectListItem>();
            ////构建角色多选框的内容；
            //foreach (var r in lst)
            //{
            //    SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = false };
            //    lststudente.Add(sli);
            //}
            //ViewBag.lstRole = lstteacher;
            //构建状态信息
            IList<SelectListItem> lstStatus = new List<SelectListItem>() 
            { 
                 new SelectListItem(){Value="1",Text="激活",Selected=true},
                 new SelectListItem(){Value="2",Text="禁用",Selected=false}
            };
            ViewBag.lstStatus = lstStatus;

            //获取课程信息
            IList<SelectListItem> courseList = new List<SelectListItem>();
            //TeacherList.Insert(0, new SelectListItem() { Text = "===请选择===", Value = "0" });
            IList<Course> CourseList = Container.Instance.Resolve<ICourseService>().GetAll();
            foreach (Course c in CourseList)
            {
                courseList.Add(new SelectListItem() { Value = c.ID.ToString(), Text = c.Name });
            }
            ViewBag.courseList = courseList;

            //获取职务信息
            //IList<SelectListItem> dictionaryList = new List<SelectListItem>();
            //dictionaryList.Insert(0, new SelectListItem() { Text = "===请选择===", Value = "0" });
            //{
            //    IList<Dictionary> postLst = Container.Instance.Resolve<IDictionaryService>().GetAll();
            //    foreach (Dictionary c in postLst)
            //    {
            //        if (c.DicType == "Post")
            //        {
            //            dictionaryList.Add(new SelectListItem() { Value = c.ID.ToString(), Text = c.Name });
            //        }

            //    }
            //}


            //ViewBag.dictionaryList = dictionaryList;

            //获取组织机构信息
            //IList<SelectListItem> orgList = new List<SelectListItem>();
            //orgList.Insert(0, new SelectListItem() { Text = "===请选择===", Value = "0" });
            //IList<Organization> classLst = Container.Instance.Resolve<IOrganizationService>().GetAll();
            //foreach (Organization c in classLst)
            //{
            //    orgList.Add(new SelectListItem() { Value = c.ID.ToString(), Text = c.OrgName });
            //}
            //ViewBag.orgList = orgList;
            return View(teacher);

        }

        /// <summary>
        /// 创建教师
        /// </summary>
        /// <param name="student">教师实体</param>
        /// <param name="roleIDs">教师IDS</param>
        /// <param name="statusValue">教师状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(Teacher teacher, string roleIDs = "", string statusValue = "0", string dictionaryId = "0", string organizationId = "0")
        {
            try
            {
                //拆分学生字符串；
                string[] arrIds = roleIDs.Split(',');
                IList<Course> courseList = new List<Course>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //根据ID查找教师信息
                        courseList.Add(Container.Instance.Resolve<ICourseService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建实体

                teacher.CourseList = courseList;
                //if (dictionaryId == "0" || dictionaryId == "")
                //{
                //    dictionaryId = null;
                //}
                //else
                //{
                //    teacher.Position = Container.Instance.Resolve<IDictionaryService>().GetEntity(Int32.Parse(dictionaryId));
                //}
                //if (organizationId == "0" || organizationId == "")
                //{
                //    organizationId = null;
                //}
                //else
                //{
                //    teacher.Organization = Container.Instance.Resolve<IOrganizationService>().GetEntity(Int32.Parse(organizationId));
                //}


                //保存到数据库中

                Container.Instance.Resolve<ITeacherService>().Add(teacher);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            //根据ID 查询要修改的实体
            Teacher entity = Container.Instance.Resolve<ITeacherService>().GetEntity(id);
            //查询所有教师信息；
            IList<Teacher> teacherList = Container.Instance.Resolve<ITeacherService>().GetAll();
            //查询所有课程信息
            IList<Course> courseList = Container.Instance.Resolve<ICourseService>().GetAll();
            IList<SelectListItem> courselist = new List<SelectListItem>();
            foreach (Course r in courseList)
            {
                bool isExist = false;
                //查找是否存在该用户的角色列表中；
                int count = entity.CourseList.Where(o => o.ID == r.ID).Count();
                //如果>0，则要被选中，否则不勾选；
                if (count > 0)
                { isExist = true; }
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = isExist };
                courselist.Add(sli);
            }
            ViewBag.courselist = courselist;
            //TeacherList.Insert(0, new Teacher() { ID = 0, Name = "===请选择===", TeacherCode = "000" });
            //List<Dictionary> dictionaryList = new List<Dictionary>();
            //dictionaryList = Container.Instance.Resolve<IDictionaryService>().Query(new List<ICriterion>() { Expression.In("ID", new int[] { 1, 2, 3, 4, 5, 6 }) }).ToList();
            //dictionaryList.Insert(0, new Dictionary() { ID = 0, Name = "===请选择===", DicType = "000", DicTypeName = "000" });
            //ViewBag.dictionaryList = dictionaryList;

            //IList<SelectListItem> dictionaryList = new List<SelectListItem>();
            //dictionaryList.Insert(0, new SelectListItem() { Text = "===请选择===", Value = "0" });
            //{
            //    IList<Dictionary> majorLst = Container.Instance.Resolve<IDictionaryService>().GetAll();
            //    foreach (Dictionary c in majorLst)
            //    {
            //        if (c.DicType == "Major")
            //        {
            //            dictionaryList.Add(new SelectListItem() { Value = c.ID.ToString(), Text = c.Name });
            //        }

            //    }
            //}

            //List<Organization> orgList = new List<Organization>();
            //orgList = Container.Instance.Resolve<IOrganizationService>().GetAll().ToList();
            //orgList.Insert(0, new Organization() { ID = 0, OrgName = "===请选择===", OrgCode = "000" });
            //ViewBag.orgList = orgList;


            //构建状态，并标记是否被选中；
            IList<SelectListItem> lstActive = new List<SelectListItem>();
            SelectListItem itm = new SelectListItem() { Value = "1", Text = "激活", Selected = false };
            if (entity.IsActive.Equals(1))
            {
                itm.Selected = true;
            }
            lstActive.Add(itm);
            itm = new SelectListItem() { Value = "0", Text = "禁用", Selected = false };
            if (entity.IsActive.Equals(0))
            {
                itm.Selected = true;
            }

            lstActive.Add(itm);
            ViewBag.lstIsActive = lstActive;
            return View(entity);
        }

        [HttpPost]
        public ActionResult Edit(int id, Teacher entity, string roleIDs = "", string statusValue = "0", string dictionaryId = "0", string organizationId = "0")
        {

            //根据ID获取需要修改的教师；
            Teacher teacher = Container.Instance.Resolve<ITeacherService>().GetEntity(id);
            try
            {
                string[] arrIds = roleIDs.Split(',');
                IList<Course> courseList = new List<Course>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //查询当前ID的角色，并添加到角色列表中
                        courseList.Add(Container.Instance.Resolve<ICourseService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建学生实体
                //stu.SysRoleList = roleList;
                //user.Password = AppHelper.EncodeMd5(user.Password);
                teacher.Name = entity.Name;
                teacher.TeacherCode = entity.TeacherCode;
                //tea.Sex = entity.Sex;
                teacher.Phone = entity.Phone;
                teacher.IsActive = Int32.Parse(statusValue);
                teacher.CourseList = courseList;
                //if (entity.Password != null && entity.Password != "")
                //{
                //    stu.Password = AppHelper.EncodeMd5(entity.Password);
                //}
                //if (dictionaryId == "0" || dictionaryId == "")
                //{
                //    tea.Position = null;
                //}
                //else
                //{
                //    tea.Position = Container.Instance.Resolve<IDictionaryService>().GetEntity(Int32.Parse(dictionaryId));
                //}

                //if (organizationId == "0" || organizationId == "")
                //{
                //    tea.Organization = null;
                //}
                //else
                //{
                //    tea.Organization = Container.Instance.Resolve<IOrganizationService>().GetEntity(Int32.Parse(organizationId));
                //}
                //修改实体，保存
                Container.Instance.Resolve<ITeacherService>().Update(teacher);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 操作
        public ActionResult SwitchStatus(int id, string type)
        {
            Teacher ther = Container.Instance.Resolve<ITeacherService>().GetEntity(id);
            if (type.Equals("Active"))
            {
                ther.IsActive = 1;
            }
            else if (type.Equals("Enabled"))
            {
                ther.IsActive = 0;
            }
            Container.Instance.Resolve<ITeacherService>().Update(ther);
            return RedirectToAction("Index");//跳转到列表页面
        }

        public ActionResult Delete(int id)
        {
            Teacher teacher = Container.Instance.Resolve<ITeacherService>().GetEntity(id);
            Container.Instance.Resolve<ITeacherService>().Delete(teacher);
            return RedirectToAction("Index");
        }
        #endregion
	}
}